
import ButtonManager from './ButtonManager.js'; // 导入按钮管理模块

const BatchEnrollActivity = {
  buttonId: 'batchEnrollActivity', // 按钮 ID
  defaultText: '5. 一次性报名全部活动', // 默认按钮文本

  // 初始化函数
  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this)); // 绑定点击事件
  },

  // 点击事件处理函数
  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '5. 一次性报名全部活动-处理中...', true); // 更新按钮状态为加载中
    ButtonManager.disableAllButtons(this.buttonId); // 禁用其他按钮

    try {
      const minimumActivityPrices = Number(minimumActivityPriceInput.value.trim());
      const minimumActivityPrice = Math.floor(minimumActivityPrices*100)
      console.log('报名活动',minimumActivityPrice)
      if(isNaN(minimumActivityPrice)){
        alert('请输入报名活动最低价格')
        return
      }

      if (minimumActivityPrice && minimumActivityPrice >= 5800) {
        console.log("输入的报名活动最低价格:", minimumActivityPrice);
        // 这里可以添加更多的逻辑，比如将报名活动最低价格存储到 localStorage 或者发送到后台脚本
      }else {
        console.log('请输入报名活动最低价格/不能低于58')
        alert('请输入报名活动最低价格/不能低于58')
        return
      }


      const { mallId, antiContent } = await new Promise((resolve) => {
        chrome.storage.local.get(['mallId', 'antiContent'], resolve); // 从本地存储获取 mallId 和 antiContent
      });

      if (!mallId || !antiContent) {
        console.error("mallId 或 antiContent 未找到"); // 检查是否获取到必要参数
        return;
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前标签页

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id }, // 注入脚本到当前标签页
        func: executeBatchEnrollActivity, // 执行报名活动逻辑
        args: [mallId, antiContent,minimumActivityPrice], // 传递参数
      });

      if (results && results[0] && results[0].result) {
        console.log("报名活动完成，返回数据:", results[0].result); // 输出报名活动结果
      } else {
        console.error("未获取到有效数据"); // 输出错误信息
      }
    } catch (error) {
      console.error("报名活动失败:", error); // 捕获错误
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText); // 恢复按钮状态
      ButtonManager.enableAllButtons(); // 启用所有按钮
    }
  },
};

// 报名活动逻辑函数
function executeBatchEnrollActivity(j_mallid, j_anti_content, j_smallPrice = 5800) {
  console.log(j_smallPrice)
  return new Promise((resolve, reject) => {
    console.log("开始执行一次性报名全部活动逻辑...");
    console.log("接收到的参数:", { j_mallid, j_anti_content });

    let j_time = Math.floor(Math.random() * 2) * 1000 + 1000;
    let j_body = { "needSessionItem": true, "needCanEnrollCnt": true };
    let j_rowCount = 50; // 一次查询可报名商品数量进行报名
    let j_activityListArr = []; // 可报名的活动

    // 获取活动列表
    function j_activitylist() {
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gambit/marketing/enroll/activity/list", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/activity/marketing-activity',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_body),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            let activityData = data.result.activityList[data.result.activityList.length - 1];
            activityData.thematicList.forEach((item, index) => {
              if (item.canEnrollTotal > 0) {
                j_activityListArr.push({ id: item.activityThematicId, name: item.activityThematicName, type: activityData.activityType });
              }
            });
            console.log('可报名的活动', j_activityListArr);
            j_match(0);
          } else {
            console.warn('获取活动列表失败');
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 查询可报名商品
    let j_matchbody = { "rowCount": j_rowCount, "addSite": true };
    let j_matchPageNum = 1; // 查询可报名商品页码
    let j_matchPagesNum = 1; // 查询可报名商品总页码
    let j_smallPriceArr = []; // 价格过低的数据
    let j_total = 0; // 单个活动累计报名成功数
    let j_allTotal = 0; // 所有活动累计报名成功数量
    let j_matchListArr = [];
    // let j_smallPrice = 5800; // 最小提交活动的价格

    function j_match(index = 0) {
      let i = index;
      if (j_matchPageNum === 1) {
        console.log('正在查询活动:', j_activityListArr[i].name);
      }
      j_matchbody.activityType = j_activityListArr[i].type;
      j_matchbody.activityThematicId = j_activityListArr[i].id;

      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gambit/marketing/enroll/scroll/match", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/activity/marketing-activity/detail-new?type=' + j_matchbody.activityType + '&thematicId=' + j_matchbody.activityThematicId,
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_matchbody),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            console.log(j_activityListArr[i].name + '页码:' + j_matchPageNum, '总页数:' + j_matchPagesNum, data.result.matchList);
            j_matchbody.searchScrollContext = data.result.searchScrollContext;
            if (j_matchPageNum === 1) {
              j_matchPagesNum = Math.ceil(data.result.stillCount / 50);
            }

            if (data.result.hasMore) {
              if (j_matchPageNum <= j_matchPagesNum) {
                console.log(j_matchPageNum, '查询' + j_activityListArr[i].name + '活动中...');
                j_matchPageNum++;
              }
              if (data.result.matchList.length > 0) {
                j_matchListArr = [...j_matchListArr, ...data.result.matchList];
                setTimeout(function () { j_submit(data.result.matchList, i); }, j_time);
              } else {
                setTimeout(function () { j_match(i); }, j_time);
              }
            } else {
              console.log(j_activityListArr[i].name + '没有更多了', j_activityListArr[i].name + '累计报名成功：' + j_total);
              console.log(j_activityListArr[i].name + '低价商品', j_smallPriceArr);

              // 重置数据
              j_matchPageNum = 1;
              j_matchPagesNum = 1;
              j_total = 0;
              j_matchListArr = [];
              j_smallPriceArr = [];
              i++;
              delete j_matchbody.searchScrollContext;
              if (j_activityListArr.length > i) {
                setTimeout(function () { j_match(i); }, j_time);
              }
            }
          } else {
            if (data.errorMsg.includes('当前专题已结')) {
              setTimeout(function () { j_match(i + 1); }, j_time);
            } else {
              setTimeout(function () { j_match(i); }, j_time);
            }
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 提交数据
    function j_submit(arr, i) {
      let productList = [];
      let sessionIds = []; // 站点id(美国)
      arr.forEach((item, index) => {
        sessionIds = item.suggestEnrollSessionIdList;
        let skcListArr = [];
        item.skcList.forEach((itemSub, indexSub) => {
          if (itemSub.skuList[0].sitePriceList[0].suggestActivityPrice > j_smallPrice) {
            let obj = {
              "skcId": itemSub.skcId,
              "siteActivityPriceList": [
                {
                  "activityPrice": itemSub.skuList[0].sitePriceList[0].suggestActivityPrice,
                  "siteId": itemSub.skuList[0].sitePriceList[0].siteId
                }],
              "skuList": []
            };
            let skuList = [];
            itemSub.skuList.map(i => {
              skuList.push({ "skuId": i.skuId });
            });
            obj.skuList = skuList;
            skcListArr.push(obj);
          } else {
            j_smallPriceArr.push({
              skcId: item.skcId,
              activityPrice: itemSub.skuList[0].sitePriceList[0].suggestActivityPrice
            });
          }
        });
        if (skcListArr.length > 0) {
          let objs = {
            "productId": item.productId,
            "activityStock": item.suggestActivityStock,
            "skcList": skcListArr,
            "sessionIds": sessionIds
          };
          productList.push(objs);
        }
      });
      let submitbody = {
        "activityType": j_activityListArr[i].type,
        "activityThematicId": j_activityListArr[i].id,
        "productList": productList
      };
      console.log(j_activityListArr[i].name + '报名活动数据', submitbody);
      if (submitbody.productList.length > 0) {
        fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gambit/marketing/enroll/submit", {
          method: 'POST',
          headers: {
            accept: '*/*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-content': j_anti_content,
            'cache-control': 'max-age=0',
            'content-type': 'application/json',
            mallid: j_mallid,
            priority: 'u=1, i',
            'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin'
          },
          referrer: 'https://seller.kuajingmaihuo.com/activity/marketing-activity/detail-new?type=13&thematicId=25021366348028',
          referrerPolicy: 'strict-origin-when-cross-origin',
          body: JSON.stringify(submitbody),
          mode: 'cors',
          credentials: 'include'
        })
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          })
          .then(data => {
            if (data.success) {
              console.log(j_activityListArr[i].name + '报名活动成功:' + submitbody.productList.length, j_activityListArr[i].name + '累计报名活动成功:' + j_total, '累计报名活动成功:' + j_allTotal);
              j_total += submitbody.productList.length;
              j_allTotal += j_total;
              setTimeout(function () { j_match(i); }, j_time);
            } else {
              console.error('报名失败,' + data.errorMsg);
              console.log(submitbody);
              setTimeout(function () { j_submit(arr, i); }, j_time);
            }
          })
          .catch(error => {
            console.error('There was a problem with your fetch operation:', error);
            reject(error);
          });
      } else {
        console.log('没有高于', j_smallPrice, '的价格');
        setTimeout(function () { j_match(i); }, j_time);
      }
    }

    // 开始执行逻辑
    j_activitylist();
  });
}

export default BatchEnrollActivity; // 导出模块